﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;
using System.Web.Configuration;

namespace WXYW
{
    public partial class Gathering : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitialPage();
            }
        }

        #region 页面数据初绑定
        private void InitialPage()
        {
            ApplicationProductService service = new ApplicationProductService();
            ApplicationQuatationFormModel model = service.GetQuatationFormModelProducts(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
            rmaCodeLabel.Text = model.ApplicationCode;
            shouldPayLabel.Text = model.TotalPrices.ToString();
            connectPersonLabel.Text = model.Client.ContactPerson;
            companyNameLabel.Text = model.Client.FullName;
            phoneNumberLabel.Text = model.Client.UserPhone;
            shouldPayLabel.Text = model.TotalPrices.ToString();
            dateTextBox.Text = DateTime.Now.ToString("yyyy-MM-dd");
            receiverTextBox.Text = ContextService.CurrentAccount.ContactPerson;
            companyAddressLbl.Text = model.Client.UserAddress;

            ProductGridView.DataSource = model.Products;
            ProductGridView.DataBind();


            ApplicationService appservice = new ApplicationService();
            ApplicationForm applicationForm = appservice.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
            if (!applicationForm.ApplicationPicture.IsLoaded)
            {
                applicationForm.ApplicationPicture.Load();
            }
            List<ApplicationPicture> picturelist = applicationForm.ApplicationPicture.Where(p => p.Type == (int)PictureType.ConfirmProduct || p.Type == (int)PictureType.MaintainProduct).ToList();
            Table table = new Table();
            table.Rows.Add(new TableRow());
            table.Rows.Add(new TableRow());
            foreach (ApplicationPicture picture in picturelist)
            {
                TableCell celllImage = new TableCell();
                Image imageControl = new Image();
                imageControl.Height = 100;
                imageControl.ImageUrl = "Picture/" + picture.PictureNameOnServer;
                imageControl.Attributes.Add("OnClick", "window.open('ImageDetail.aspx?Name=" + picture.PictureNameOnServer + "')");
                celllImage.Controls.Add(imageControl);
                table.Rows[0].Cells.Add(celllImage);

                TableCell cellName = new TableCell();
                Label label = new Label();
                label.Text = picture.PictureName;
                cellName.Controls.Add(label);
                table.Rows[1].Cells.Add(cellName);
            }
            picturePanel.Controls.Add(table);
        }

        protected void ProductGridView_RowDataBound1(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();
            }
        }
        #endregion

        // 点击提交按钮事件处理程序
        protected void submitLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                double realpay = 0;
                if (double.TryParse(realPayTextBox.Text, out realpay))
                {
                    ApplicationService service = new ApplicationService();
                    ApplicationForm form = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                    if (!form.GatheringReference.IsLoaded)
                    {
                        form.GatheringReference.Load();
                    }
                    if (form.Gathering == null)
                    {
                        form.Gathering = new DAL.Gathering
                         {
                             PayDateTime = Convert.ToDateTime(dateTextBox.Text),
                             RealPay = realpay,
                             Receiver = receiverTextBox.Text,
                             Remark = remarkTextBox.Text,
                             ReasonOfNotReceiveMoney = notReceiveMoneyReasonDDL.SelectedValue,
                             CreateDate = DateTime.Now
                         };
                    }
                    else
                    {
                        form.Gathering.RealPay += double.Parse(realPayTextBox.Text);
                        form.Gathering.PayDateTime = DateTime.Now;
                    }

                    form.Gathering.RealPayDif = double.Parse(shouldPayLabel.Text) - form.Gathering.RealPay;
                    if (form.CompleteDateTime.HasValue)
                    {
                        form.Status = "维修完毕待发货";
                        service.UpdateApplication(form);
                        Response.Write(string.Format("<script language='JavaScript'> alert( '该单已完成收款，将流转至维修完毕待发货，请及时发货并通知客户收货！');location.href= 'ListConfirmGathering.aspx' </script>"));
                    }
                    else{
                        service.UpdateApplication(form);
                        Response.Write(string.Format("<script language='JavaScript'> alert( '该单已完成收款，请继续完成维修！');location.href= 'ListConfirmGathering.aspx' </script>"));
                    }
           

                    //如果所有产品都维修完毕 2013.09.01
                    //ApplicationProductService productservice = new ApplicationProductService();
                    //productservice.FinishMaintains(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                    //ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('已付款待修');", true);
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('实付货款格式不正确');", true);
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "Gathering.aspx::submitLinkButton_Click");
                ClientScript.RegisterStartupScript(this.GetType(), "tip", string.Format("alert('提交过程中发生错误，请截图保存该错误信息并联系管理员！错误原因：{0}');", ex.Message), true);
            }
        }        

        // 点击图片上传按钮事件处理程序
        protected void uploadButton_Click(object sender, EventArgs e)
        {
            string fileType = string.Empty;
            string fileName = string.Empty;
            string fileNameOnServer = string.Empty;
            if (fileUploadPicture.HasFile)
            {
                fileType = fileUploadPicture.FileName.Substring(fileUploadPicture.FileName.LastIndexOf("."));
                fileName = fileUploadPicture.FileName;
                fileNameOnServer = Guid.NewGuid() + fileType;
                fileUploadPicture.SaveAs(Server.MapPath("Picture/" + fileNameOnServer));
            }
            ApplicationService service = new ApplicationService();
            ApplicationForm form = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
            ApplicationPicture picture = new ApplicationPicture
            {
                PictureName = fileName,
                PictureNameOnServer = fileNameOnServer,
                Type = (int)PictureType.MaintainProduct,
                UploadPerson = ContextService.CurrentAccount.UserID
            };
            form.ApplicationPicture.Add(picture);
            service.UpdateApplication(form);
            InitialPage();
        }

        // 点击返回按钮事件处理程序
        protected void backLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListConfirmGathering.aspx");
        }
    }
}
